<template>
  <div class="writeoff-report">
    <!-- 搜索区域 -->
    <div class="search-area">
      <el-input v-model="searchParams.write_off_code" placeholder="请输入单据编号" style="width: 220px" />

      <el-date-picker 
        v-model="dateRange" 
        type="daterange" 
        range-separator="-" 
        start-placeholder="开始日期" 
        end-placeholder="结束日期" 
        @change="handleDateChange"
      />

      <el-select v-model="searchParams.business_type" placeholder="业务类型" style="width: 120px">
        <el-option label="(空)" value="" />
        <el-option label="预收冲应收" value="yscys" />
        <el-option label="预付冲应付" value="yfcyf" />
        <el-option label="应收冲应付" value="yscyf" />
        <el-option label="应收转应收" value="yszys" /> <!-- 修正错误value：yfzys→yszys -->
        <el-option label="应付转应付" value="yfzyf" />
      </el-select>
      <el-button @click="handleReset">重置</el-button>
      <el-button type="primary" @click="getWriteoffList">查询</el-button> <!-- 绑定查询事件 -->
    </div>

    <!-- 操作按钮区域 -->
    <div class="action-buttons">
      <el-button type="primary" @click="toWriteoffDocument()">新增</el-button>
      <el-button type="danger" @click="handleBatchDelete">删除</el-button>
    </div>

    <!-- 表格区域 -->
    <el-table
      :data="writeoffList.length > 0 ? writeoffList : emptyTableData"
      border
      stripe
      :row-class-name="rowClassName"
      :header-cell-style="headerCellStyle"
    >
      <!-- 序号列 -->
      <el-table-column type="index" label="序号" width="65" align="center" />

      <!-- 复选框列 -->
      <el-table-column type="selection" width="40" />

      <!-- 操作列 -->
      <el-table-column label="操作" width="90" align="center">
        <!-- 关键修复：添加 { row } 接收行数据 -->
        <template #default="{ row }">
          <div class="table-actions">
            <el-button type="text" @click="handleEdit(row)" class="edit-btn">编辑</el-button>
            <el-button type="text" @click="handleDelete(row)" class="delete-btn">删除</el-button>
          </div>
        </template>
      </el-table-column>

      <!-- 单据日期 -->
      <el-table-column prop="docDate" label="单据日期" width="110" sortable />

      <!-- 单据编号 -->
      <el-table-column prop="docNo" label="单据编号" width="155" sortable />

      <!-- 业务类型（显示文字） -->
      <el-table-column label="业务类型" width="110">
        <template #default="{ row }">
          <span v-if="!row.isPlaceholder">{{ getBusinessTypeText(row.businessType) }}</span>
        </template>
      </el-table-column>

      <!-- 客户1/供应商1（显示名称） -->
      <el-table-column label="客户1/供应商1" width="140">
        <template #default="{ row }">
          <span v-if="!row.isPlaceholder">{{ row.party1Name || row.party1 || "无" }}</span>
        </template>
      </el-table-column>

      <!-- 客户2/供应商2（显示名称） -->
      <el-table-column label="客户2/供应商2" width="140">
        <template #default="{ row }">
          <span v-if="!row.isPlaceholder">{{ row.party2Name || row.party2 || "无" }}</span>
        </template>
      </el-table-column>

      <!-- 核销金额 -->
      <el-table-column
        prop="writeoffAmount"
        label="核销金额"
        width="100"
        align="right"
      />

      <!-- 制单人 -->
      <el-table-column prop="creator" label="制单人" width="100" />

      <!-- 备注 -->
      <el-table-column prop="remark" label="备注" min-width="120" />

    </el-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import dayjs from 'dayjs';
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter } from "vue-router";
import axios from 'axios';
const router = useRouter();
const multipleSelection = ref([]);
// 业务类型映射
const businessTypeMap = {
  'yscys': '预收冲应收',
  'yfcyf': '预付冲应付',
  'yscyf': '应收冲应付',
  'yszys': '应收转应收',
  'yfzyf': '应付转应付'
};

// 存储客户/供应商列表
const customerList = ref([]);
const supplierList = ref([]);

// 表格数据
const writeoffList = ref([]);
// 生成5行虚拟空数据
// const emptyTableData = ref(
//   Array(5).fill({
//     isPlaceholder: true, // 标记为占位行
//     docDate: "",
//     docNo: "",
//     businessType: "",
//     party1: "",
//     party1Name: "",
//     party2: "",
//     party2Name: "",
//     writeoffAmount: 0,
//     creator: "",
//     remark: "",
//   })
// );
// 日期范围
const dateRange = ref([]);


// 搜索参数
const searchParams = reactive({
  write_off_code: '',
  business_type: '',
  startDate: '',
  endDate: ''
});

// 页面加载时初始化：获取客户/供应商列表 + 核销单列表
onMounted(() => {
  Promise.all([getCustomerList(), getSupplierList()]).then(() => {
    getWriteoffList(); // 先加载基础数据，再查核销单
  });
});
// 客户列表
const getCustomerList = async () => {
  try {
    const response = await axios.get("/finance/customerPage", { params: { pageNum: 1, pageSize: 1000 } });
    if (response.data.code === 5200) {
      customerList.value = response.data.customerList;
      console.log('客户列表customerList',customerList.value)
    }
  } catch (error) {
    console.error("获取客户列表失败：", error);
  }
};
// 供应商列表
const getSupplierList = async () => {
  try {
    const response = await axios.get("/finance/getSupplierList", { 
      params:{pageNum:1,pageSize:100}
    });
    if (response.data.code === 5200) {
      console.log('供应商列表supplierList',response.data.supplierList.pageInfo.list)
      supplierList.value = response.data.supplierList.pageInfo.list;
    } else {
      ElMessage.error("获取供应商失败：" + response.data.msg);
    }
  } catch (error) {
    console.error("获取供应商出错：", error);
    ElMessage.error("网络错误，无法获取供应商数据");
  }
};

// 核销单列表 + 数据格式化（编码转文字/名称）
const getWriteoffList = async () =>{
  try {
    const response = await axios.get("/finance/getWriteoff", { params: searchParams });
    if (response.data.code === 5200) {
      const rawList = response.data.writeoffList || [];
      console.log('返回的rawList',rawList)
      writeoffList.value = rawList.map(item => {
        let party1Name = '';
        if (item.write_off_present) { 
          const customer = customerList.value.find(c => c.code === item.write_off_present);
          const supplier = supplierList.value.find(s => s.code === item.write_off_present);
          party1Name = customer?.name || supplier?.name || '';
        }

        let party2Name = '';
        if (item.write_off_target) { 
          const customer = customerList.value.find(c => c.code === item.write_off_target);
          const supplier = supplierList.value.find(s => s.code === item.write_off_target);
          party2Name = customer?.name || supplier?.name || '';
        }

        return {
          write_off_id: item.write_off_id,
          write_off_code: item.write_off_code,
          docDate: item.document_date ? dayjs(item.document_date).format('YYYY-MM-DD') : '', 
          docNo: item.write_off_code || '', 
          businessType: item.business_type || '', 
          party1: item.write_off_present || '',
          party1Name: party1Name, 
          party2: item.write_off_target || '', 
          party2Name: party2Name, 
          writeoffAmount: item.total_amount || item.current_written_off_all_amount,
          creator: item.creator || '', 
          remark: item.remark || '' 
        };
      });
      console.log('格式化后的核销单列表：', writeoffList.value);
    } else {
      ElMessage.error("获取核销单失败：" + response.data.msg);
      writeoffList.value = [];
    }
  } catch (error) {
    console.error("获取核销单出错：", error);
    ElMessage.error("网络错误，无法获取核销单数据");
    writeoffList.value = [];
  }
};

// // 编辑
const handleEdit = (row) => {
  router.push({
    path: '/finance/writeoff-documents',
    query: {
      code: row.write_off_code,
      companyCode: 'GS0001'
    }
  });
}
// 删除
const handleDelete = async (row) => {
  console.log('接受的row',row)
  try {
    await ElMessageBox.confirm('确定删除该收款单吗？', '提示', {
      type: 'warning'
    });
    const response = await axios.get(`/finance/deleteWriteoff?write_off_id=${row.write_off_id}`);
    if (response.data.code === 5200) {
      ElMessage.success('删除成功');
      getWriteoffList();
    } else {
      console.log('删除失败',response.data)
      ElMessage.error(response.data.msg || '删除失败');
    }
  } catch (error) {
    console.log('删除失败',error)
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// // 批量删除
const handleBatchDelete = async () => {
  if (multipleSelection.value.length === 0) {
    ElMessage.warning('请选择要删除的收款单');
    return;
  }
  
  try {
    await ElMessageBox.confirm(`确定删除选中的记录吗？`, '提示', {
      type: 'warning'
    });
    
    // 批量删除逻辑
    const deletePromises = multipleSelection.value.map(item => 
      axios.get(`/finance/deleteWriteoff?write_off_id=${item.write_off_id}`)
    );
    
    await Promise.all(deletePromises);
    ElMessage.success('删除成功');
    getWriteoffList();
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败');
    }
  }
};

// 业务类型转文字
const getBusinessTypeText = (code) => {
  return businessTypeMap[code] || '未知类型';
};

// 重置搜索
const handleReset = () => {
  Object.keys(searchParams).forEach(key => {
    searchParams[key] = '';
  });
  dateRange.value = [];
  getWriteoffList(); 
};

// 日期变化处理
const handleDateChange = (dates) => {
  if (dates && dates.length === 2) {
    searchParams.startDate = dayjs(dates[0]).format('YYYY-MM-DD');
    searchParams.endDate = dayjs(dates[1]).format('YYYY-MM-DD');
  } else {
    searchParams.startDate = '';
    searchParams.endDate = '';
  }
};
// 表头样式
const headerCellStyle = {
  backgroundColor: "#f5f7fa",
  fontWeight: "normal",
  color: "#606266",
};
// 行样式处理
const rowClassName = ({ row }) => {
  return row.isPlaceholder ? "placeholder-row" : "";
};

// 跳转新增页面
const toWriteoffDocument = () => {
  router.push("/finance/writeoff-documents");
};
</script>

<style scoped>
.writeoff-report {
  padding: 15px;
  background-color: #fff;
  min-height: 500px;
}

/* 搜索区域样式 */
.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  flex-wrap: wrap;
  gap: 10px;
}

/* 操作按钮区域 */
.action-buttons {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
  gap: 8px;
}

/* 表格样式 */
::v-deep .el-table {
  border: 1px solid #e4e7ed;
}

/* 占位行样式 */
::v-deep .placeholder-row {
  height: 48px; /* 固定行高 */
  opacity: 0.3;
}

/* 操作按钮样式 */
.table-actions {
  display: flex;
  justify-content: center;
  gap: 5px;
}

.edit-btn {
  color: #409eff;
  padding: 0;
}

.delete-btn {
  color: #f56c6c;
  padding: 0;
}

:deep(.el-table .el-table__row:hover > td) {
  background-color: #fff4bf !important;
}
</style>